﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DTO;
using System.IO;
using BUS;
using System.Xml;
using System.Data.SqlClient;
namespace GPBenhLanh
{
    public partial class frmKetQuaFNA : DevExpress.XtraEditors.XtraForm
    {
        public frmKetQuaFNA()
        {
            InitializeComponent();
            initControl(this);
            ByTB = 1;
        }
        TTXacNhanDTO _xn;
        public TTXacNhanDTO Xn
        {
            get { return _xn; }
            set { _xn = value; }
        }

        private TTKetQuaDTO kq = new TTKetQuaDTO();

        string _sThuMucLuu;
        public string sThuMucLuu
        {
            get { return _sThuMucLuu; }
            set { _sThuMucLuu = value; }
        }
        //1: nhập kết quả theo số tiêu bản
        //0: nhâp kết quả theo cách truyền thống
        private int ByTB = 0;

        private Bitmap bmHinh1 = null;
        private Bitmap bmHinh2 = null;
        private Bitmap bmHinh3 = null;
        private Bitmap bmHinh4 = null;
        private int ketqua = 0;
        private int flagLuu = 1;
        private int flagKQ = 0;
        private int lan = 0;
        private DateTime cDate = DateTime.Today;//ngay xac nha cua ket qua
        private DateTime cDate2 = DateTime.Today;//ngay xac nha cua ket qua
        private int[] dataTran = new int[4];//dataTran[0]: lan ; dataTran[1]: 1=reload 0=No reload
        private static string strPathHinh = "";
        public void getPathStrHinh()
        {
            string _sConnection = Uit.it_Conn.getConnectString("pathStrHinh");
            strPathHinh = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }

        public delegate void MyDelege2(object sender, Object data);
        public event MyDelege2 thoatEven;

        private int[] isImg= new int[4]{0,0,0,0};

        public frmKetQuaFNA(TTXacNhanDTO xnf)
        {
            InitializeComponent();
            Xn = xnf;
            initControl(this);
        }

        public static string _strConnectPK;
        SqlConnection conpk;

        /// <summary>
        /// get thong tin ket noi den database phKham
        /// </summary>
        public void getConnectStringPK()
        {
            string _sConnection = Uit.it_Conn.getConnectString("ConnectPhkham");
            _strConnectPK = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }

        public void CnPKham()
        {
            if (conpk == null || conpk.State == ConnectionState.Closed)
            {
                getConnectStringPK();
                conpk = new SqlConnection();
                conpk = Uit.it_Conn.getConnect(_strConnectPK);
            }
        }

        private void initControl(Control ctrl)
        {

            // Bỏ qua điều kiểm trừ khi nó là TextBox.
            if (ctrl.Tag == "text")
            {
                ctrl.Text = "";
            }

            // Xử lý các điều kiểm một cách đệ quy.
            // Điều này cần thiết khi có một điều kiểm chứa nhiều 
            // điều kiểm khác (ví dụ, khi bạn sử dụng Panel, 
            // GroupBox, hoặc điều kiểm container nào khác).
            foreach (Control ctrlChild in ctrl.Controls)
            {
                initControl(ctrlChild);
            }
        }

        private void loadComboBox()
        {
            DataTable dtbs = GetThongTinSearchBUS.SearchDSBacSi();
            comBacSi.Properties.DataSource = dtbs;
            comKTV.Properties.DataSource = GetThongTinSearchBUS.SearchDSKTV();
            //comBacSi.EditValue = 267;
            comKTV.EditValue = 1;

            DataTable dtBSCD = GetThongTinSearchBUS.SearchDSBacSiCD();
            combscd.Properties.DataSource = dtBSCD;
            //combscd.EditValue = IDBacSiCD;

            //list phau thuat vien
            comPTV.Properties.DataSource = dtBSCD;
            comPTV.EditValue = PTVien;

            comDonVi.Properties.DataSource = GetThongTinSearchBUS.SearchDonVi(conpk);
            
            comDViGuiMau.Properties.DataSource = GetThongTinSearchBUS.SearchDonViGuiMau();
        }

        private void loadTTHC()
        {
            //set thong tin hanh chinh cua benh nha
            txtHoTen.Text = Xn.HoTen;
            int Tuoi = DateTime.Today.Year - Convert.ToInt32(Xn.NamSinh);
            txtTuoi.Text = Xn.NamSinh.ToString();
            if (Xn.Gioi == true)
                txtGioi.Text = "Nam";
            else
                txtGioi.Text = "Nữ";
            txtNghe.Text = Xn.DienThoai;
            txtSoHS.Text = Xn.SoHS;
            txtSoBN.Text = Xn.SoBN;
            txtDichVu.Text = Xn.TenDVu;
            txtSoNVien.Text = Xn.SoNV;
            //txtDVChiDinh.Text = Xn.TenDViChiDinh;
            txtChuanDoan.Text = Xn.ChuanDoan;
            IDBacSiCD.Text = Xn.IDBacSiCD.ToString();
            PTVien.Text = Xn.PTVien.ToString();
            loadComboBox();
            //txtPTV.Text = comPTV.Text;
            //txtbscd.Text = combscd.Text;
            txtsotieuban.Text = Xn.SoTieuBan;
        }
  
        private void loadKQ()
        {
            //load lai kq
            DataTable dt = KQBUS.GetKetQua(txtSoBN.Text,txtSoHS.Text,txtsotieuban.Text,3);          
            if (dt.Rows.Count > 0)
            {
                comBacSi.EditValue = int.Parse(dt.Rows[0]["IDBacSiTH"].ToString());
                //combscd.EditValue = Xn.IDBacSiCD;
                comKTV.EditValue = int.Parse(dt.Rows[0]["IDKTV"].ToString());
                txtsotieuban.Text = dt.Rows[0]["SoTieuBan"].ToString();
              
                //neu da co ket qua
                if (dt.Rows[0]["KQViThe"].ToString() != ""||dt.Rows[0]["KQViThe"].ToString() != " ")
                {
                    pnlKQ.Enabled = false;
                   
                    btnLuuKetQua.Enabled = false;
                    btnSuaKQ.Enabled = true;
                    txtDaiThe1.Text = dt.Rows[0]["KQDaiThe"].ToString();
                    txtViThe1.Text = dt.Rows[0]["KQViThe"].ToString();
                    txtKetLuan1.Text = dt.Rows[0]["KetLuan"].ToString();
                    lan = 1;
                    isImg[0] = 1;

                    Xn.KQ1 = txtsotieuban.Text;
                }
                else
                {
                    btnSuaKQ.Enabled = false;
                }
            }
            else//neu chua co ket qua
            {
                lan = 1;
                txtDaiThe1.Text = "";
                txtViThe1.Text = "";
                txtKetLuan1.Text = "";
                btnLuuKetQua.Enabled = true;
                btnSuaKQ.Enabled = false;
                //control cho truong hop chua co ket qua
                btnSuaKQ.Visible = true;
                btnCapnhat.Visible = false;
                pnlKQ.Enabled = true;
                flagLuu = 0;
                flagKQ = 0;

                //set so tieu ban Cyy-XXXXX
                if (ByTB != 1)
                    txtsotieuban.Text = Xn.SoTieuBan;
            }
           
        }

        private void setDataToForm()
        {
            //load lai thong tin hanh chinh cua benh nhan
            loadTTHC();
            //load lai ket qua cho benh nhan
            loadKQ();           
        }
       
        private void LoadHinh(PictureEdit edit, ref Bitmap bm)
        {
            edit.Image = bm;
        }
        
        string path = "";
        private void LoadLaiHinhKQ(string lanthu, PictureEdit pic1, PictureEdit pic2
                                    , ref Bitmap Hinh1, ref Bitmap Hinh2)
        {
            string pathTemp_x100 = Application.StartupPath + "\\PictureTemp" +"\\x100_" 
                                   + lanthu.ToString() + ".jpg";
            //x100
            if (File.Exists(pathTemp_x100))
            {
                if (!File.Exists(sThuMucLuu + "\\x100_" + lanthu.ToString() + ".jpg"))
                {
                    File.Copy(pathTemp_x100, sThuMucLuu + "\\x100_" + lanthu.ToString() + ".jpg");
                }
            }

            string pathHinhDaLuu_x100 = sThuMucLuu + "\\x100_" + lanthu.ToString() + ".jpg";
            if (File.Exists(pathHinhDaLuu_x100))
            {
                Stream stream = File.Open(pathHinhDaLuu_x100, FileMode.Open,
                FileAccess.Read, FileShare.Delete);
                Bitmap m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close();
                Hinh1 = m_Bitmap;
                LoadHinh(pic1, ref Hinh1);
            }
            else
            {
                Hinh1 = null;
                LoadHinh(pic1, ref Hinh1);
            }
            //x400
            string pathTemp_x400 = Application.StartupPath + "\\PictureTemp"
                + "\\x400_" + lanthu.ToString() + ".jpg";
            if (File.Exists(pathTemp_x400))
            {
                if (!File.Exists(sThuMucLuu  + "\\x400_"  + lanthu.ToString() + ".jpg"))
                {
                    File.Copy(pathTemp_x400, sThuMucLuu  + "\\x400_" + lanthu.ToString() + ".jpg");
                }
            }

            string pathHinhDaLuu_x400 = sThuMucLuu + "\\" + "\\x400_" + lanthu.ToString() + ".jpg";
            if (File.Exists(pathHinhDaLuu_x400))
            {
                Stream stream = File.Open(pathHinhDaLuu_x400, FileMode.Open,
                FileAccess.Read, FileShare.Delete);
                Bitmap m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close();
                Hinh2 = m_Bitmap;
                LoadHinh(pic2, ref Hinh2);
            }
            else
            {
                Hinh2 = null;
                LoadHinh(pic2, ref Hinh2);
            }
        }
        
        private void LoadHinh()
        {           
            //load lai hinh kq
            LoadLaiHinhKQ(txtsotieuban.Text, picCL1, picCL2, ref bmHinh1, ref bmHinh2);
        }
         
        private void frmKetQua_Load(object sender, EventArgs e)
        {
            try
            {
                getPathStrHinh();                
                CreateDir();
                CnPKham();
                if (ByTB != 1)
                {
                    setDataToForm();
                    ptnByTB.Visible = false;
                }                
                loadComboBox();
               
                LoadHinh();
                if (txtKetLuan1.Text != "")
                    flagKQ = 1;
                btngo_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }            
        } 

        void frm_thoatEven(object sender, object data)
        {
            LoadHinh();
            isImg = (int[])data;
        }

        private void btnChupHinh_Click(object sender, EventArgs e)
        {
            try
            {
                frmChupHinh frmHinh = new frmChupHinh(txtsotieuban.Text, 0);
                frmHinh.sThuMucLuu = this.sThuMucLuu;
                frmHinh.thoatEven += new frmChupHinh.DelegeChupH(frm_thoatEven);
                frmHinh.sophieu = Xn.SoBN;
                
                frmHinh.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void ClearHinh(ref PictureEdit pic, ref Bitmap hinh)
        {
            if (hinh != null)
            {
                hinh.Dispose();
                hinh = null;
                pic.Image = null;
                pic.Refresh();                
            }            
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ == 0)
                {
                    DialogResult result = MessageBox.Show("Bạn Chưa lưu kết quả./n" +
                        " Bạn có muốn lưu kết quả không ?", "Thông báo", MessageBoxButtons.YesNo,
                        MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        btnLuuKetQua_Click(sender, e);
                    }
                }
                ClearHinh(ref picCL1,ref bmHinh1);
                ClearHinh(ref picCL2, ref bmHinh2);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }          
        }

        private void CreateDir()
        {
            string goc = strPathHinh;
            DateTime dt;
            if (Xn != null)
                dt = Xn.NgayNhan;
            else
                dt = DateTime.Today;
            string namthang = dt.Year.ToString() + Uit.it_String.Right("0" + dt.Month.ToString(), 2);
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4));
            }
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4));
            }
            this.sThuMucLuu = goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4);
        }

        private bool CheckSave()
        {  
            if (txtViThe1.Text == "")
            {
                ErrorProvider.SetError(txtViThe1, "Bạn phải nhập thông tin cho mô tả đại thể!");
                return false;
            }
            else
                ErrorProvider.ClearErrors();
            
            return true;
        }

        private void btnLuuKetQua_Click(object sender, EventArgs e)
        {
            try
            {
                //if (CheckSave())
                //{
                this.ketqua = 1;
                //kiem tra ket qua truoc khi luu
                //set value ket qua                
                kq.SoBN = Xn.SoBN;
                if (comBacSi.EditValue.ToString() == "")
                {
                    MessageBox.Show("Bạn phải chọn bác sĩ thực hiện!", "Thông báo");
                    return;
                }
                kq.IDBacSiTH = int.Parse(comBacSi.EditValue.ToString());
                if (comKTV.EditValue.ToString() == "")
                {
                    kq.IDKTV = 0;
                    return;
                }
                else
                    kq.IDKTV = int.Parse(comKTV.EditValue.ToString());
                kq.CDate = DateTime.Today;
                kq.SoTBan = txtsotieuban.Text;
                Boolean rs = false;
                kq.LoaiKQ = hensu.FNA;
                kq.KQDaiThe1 = txtDaiThe1.Text;
                kq.KQViThe1 = txtViThe1.Text;
                kq.KetLuan1 = txtKetLuan1.Text;
                kq.UrlHinh1 = path;
                kq.Host = Uit.it_Computer.ComputerName().ToString();
                kq.UserName = UserDTO.LoginName.ToString();
                kq.Lan = 3;
                //add 25.01.2015
                kq.SoLam = 0;
                
                kq.IDNguoiCat = 0;
                kq.NgayCat = DateTime.Now;
                kq.NgayLenLam = DateTime.Now;
                kq.IDPPNhuom = "0";
                kq.SoLamHM = 0;
                kq.GhiChu = "";
                //end add
                rs = KQBUS.InsertKetQua(kq);

                if (rs)
                {
                    rs = false;
                    if (!kq.KQDaiThe1.Equals(""))
                        rs = KQBUS.UpdateXacNhan(kq.SoBN, kq.SoTBan, 1);

                    KQBUS.UpdateFee(kq.SoBN, txtSoHS.Text, txtSoNVien.Text, true
                                , int.Parse(lblLoaiBN.Text), lblDVCode.Text, conpk);
                    if (rs)
                    {
                        dataTran[0] = lan;
                        if (lan >= 1)
                            dataTran[1] = 1;
                    }
                    btnLuuKetQua.Enabled = false;
                    btnSuaKQ.Enabled = true;
                    pnlKQ.Enabled = false;
                    flagLuu = 1;
                    flagKQ = 1;
                }
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }           
        }

        private void btnInKQ_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ == 0)
                {
                    XtraMessageBox.Show("Chưa có kết quả!", "Thông báo");
                }
                else if (flagLuu == 1)
                {
                    rptKQFNA rptKQ = new rptKQFNA();
                    SerDataToReport(rptKQ);
                    rptKQ.Print();                    
                }
                else
                {
                    XtraMessageBox.Show("Chưa lưu kết quả!", "Thông báo");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private int SerDataToReport(rptKQFNA rptKQ)
        {
            DateTime cdate = DateTime.Today, cdate2 = DateTime.Today;
            DataTable dt = KQBUS.GetKetQua(txtSoBN.Text,txtSoHS.Text,txtsotieuban.Text,3);
            if (dt.Rows.Count > 0)
            {
                rptKQ.txtSoTieuBan.Text = dt.Rows[0]["SoTieuBan"].ToString().ToUpper();
                rptKQ.txtDiaChi.Text = dt.Rows[0]["DiaChi"].ToString();
                rptKQ.txtchatbenhpham.Text = dt.Rows[0]["KQDaiThe"].ToString();
                rptKQ.txtvithe.Text = dt.Rows[0]["KQViThe"].ToString();
                string skl= dt.Rows[0]["KetLuan"].ToString();
                rptKQ.txtchatbenhpham.Text = dt.Rows[0]["ChatBP"].ToString();
                if (skl.Trim().Equals(""))
                {
                    rptKQ.txtketluan.Text = "";
                    rptKQ.lblketLuan.Visible = false;
                }
                else
                    rptKQ.txtketluan.Text = dt.Rows[0]["KetLuan"].ToString();
            }
            else
            {
                return 1;
            }           
            string gioi = "";
            if (Xn.Gioi)
                gioi = "Nam";
            else
                gioi = "Nữ";
            
            rptKQ.barSoHS.Text = Xn.SoHS;
            rptKQ.txtSoBN.Text = Xn.SoBN;
            rptKQ.txtDViChiDinh.Text = comDViGuiMau.Text;
            rptKQ.txthoten.Text = Xn.HoTen.ToUpper();
            rptKQ.txtGioiTinh.Text = gioi;
            rptKQ.txttuoi.Text = dt.Rows[0]["NamSinh"].ToString()
                                   + "(" + dt.Rows[0]["Tuoi"].ToString() + " Tuổi)";
            rptKQ.txtnghe.Text = Xn.Nghe;
            rptKQ.txtchuandoan.Text = Xn.ChuanDoan;
            rptKQ.txtngaylaymau.Text = Xn.NgayLayMau.ToString("dd/MM/yyyy");
            rptKQ.txtptv.Text = comPTV.Text;
            rptKQ.txtbscd.Text = combscd.Text;
            
            rptKQ.txtngaynhanmau.Text = Xn.NgayNhan.ToString("dd/MM/yyyy, hh:mm");
           
            rptKQ.piclan1.Image = picCL1.Image;
            rptKQ.piclan2.Image = picCL2.Image;
            cdate = DateTime.Parse(dt.Rows[0]["CDate"].ToString());

            rptKQ.txtngaythang.Text = "Ngày " + cdate.Day.ToString("00") +
                                  " Tháng " + cdate.Month.ToString("00") +
                                  " Năm " + cdate.Year.ToString("0000");
          
            if (rptKQ.piclan1.Image == null)
            {
                rptKQ.piclan1.Visible = false;
            }
            if (rptKQ.piclan2.Image == null)
            {
                rptKQ.piclan2.Visible = false;
            }
            rptKQ.txtngaygioin.Text = DateTime.Now.ToString("dd/MM/yyyy, hh:mm:ss");
            rptKQ.txtbsthuchien.Text = comBacSi.Text;
            return 0;
        }

        private void btnPrintRevew_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ != 0 && flagLuu != 0)
                {
                    rptKQFNA rptKQ = new rptKQFNA();
                    int rs = SerDataToReport(rptKQ);
                    if (rs != 0)
                    {
                        MessageBox.Show("Bạn chưa nhập kết luận!", "Thông Báo");
                        return;
                    }
                    rptKQ.ShowPreview();
                    
                }
                else
                {
                    DevExpress.LookAndFeel.UserLookAndFeel lookAndFeel = new DevExpress.LookAndFeel.UserLookAndFeel(this);
                    XtraMessageBox.Show(lookAndFeel, "Chưa lưu kết quả.\nBạn phải lưu kết quả trước");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void frmKetQua_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thoatEven != null)
            {
                thoatEven(this, dataTran);
            }
        }

        private void btnSuaKQ_Click(object sender, EventArgs e)
        {
            try
            {
                flagLuu = 0;
             
                pnlKQ.Enabled = true;
                btnLuuKetQua.Enabled = false;
                btnSuaKQ.Visible = false;
                btnCapnhat.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        /// <summary>
        /// xoa hinh kho xoa ket qua
        /// </summary>
        /// <param name="kqLan">hinh ket qua lan thu i</param>
        /// <param name="loaiHinh">loai hinh x100 hay x400</param>
        private void xoaHinh(ref PictureEdit picXoa, ref Bitmap hinhXoa
                            , string kqLan, string loaiHinh)
        {
            string urlServer = sThuMucLuu  + "\\" + loaiHinh + "_" + kqLan + ".jpg";
            string urlLocal = Application.StartupPath + "\\PictureTemp" + "\\" + loaiHinh + "_" + kqLan + ".jpg";
            if (File.Exists(urlServer))
            {
                //clear hinh
                ClearHinh(ref picXoa, ref hinhXoa);
                //xoa hinh
                File.Delete(urlServer);
            }
            if (File.Exists(urlLocal))
            {
                //clear hinh
                ClearHinh(ref picXoa, ref hinhXoa);
                //xoa hinh
                File.Delete(urlLocal);
            }
        }

        private void btnXoaKQ_Click(object sender, EventArgs e)
        {
            try
            {
                //xoa database
                bool rs = KQBUS.DeleteKQ(txtSoBN.Text,txtsotieuban.Text);

                if (rs)
                {
                    //xoa hinh
                    //xoaHinh(ref picCL1, ref bmHinh1, txtsotieuban.Text.Trim(), "X100");
                    //xoaHinh(ref picCL2, ref bmHinh2, txtsotieuban.Text.Trim(), "X400");
                  
                    //update xac nhan
                    bool kqup = false;
                    kqup = KQBUS.UpdateXacNhan(Xn.SoBN, "0", 1);
                    if (kqup)
                    {
                        //dataTran[0]: lan ; dataTran[1]: 1=reload 0=No reload
                        dataTran[0] = 0;
                        dataTran[1] = 1;
                        flagLuu = 0;
                        flagKQ = 0;
                        btngo_Click(sender, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(),"Thông Báo");
            }           
        }

        private void btnCapnhat_Click(object sender, EventArgs e)
        {
            try
            {
                kq.SoBN = Xn.SoBN;
                kq.IDBacSiTH = int.Parse(comBacSi.EditValue.ToString());
                kq.CDate = DateTime.Now;

                Boolean rs = false;                  
                kq.KQDaiThe2 = txtDaiThe1.Text;
                kq.KQViThe2 = txtViThe1.Text;
                kq.KetLuan2 = txtKetLuan1.Text;
                kq.SoTBan = txtsotieuban.Text;
                kq.UserName = UserDTO.LoginName.ToString();
                kq.CDate = DateTime.Now;
                kq.UrlHinh2 = path;
                kq.Lan = 3;
                // add 23.01.2015
                kq.SoLam = 0;
                             
                kq.IDNguoiCat = 0;
                kq.NgayCat = DateTime.Now;
                kq.NgayLenLam = DateTime.Now;
                kq.IDPPNhuom = "1";
               
                kq.IDKTV = 0;
                kq.SoLamHM = 0;
                kq.SoMauCat = 0;
                kq.GhiChu = "";
                // end add
                rs = KQBUS.UpdateKetQua(kq);                  

                if (rs)
                {
                    if (!kq.KQDaiThe2.Equals(""))
                        rs = KQBUS.UpdateXacNhan(kq.SoBN, kq.SoTBan, 1);
                    btnSuaKQ.Visible = true;
                    btnCapnhat.Visible = false;
                    pnlKQ.Enabled = false;
                    flagLuu = 1;
                    flagKQ = 1;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void tabKQ_SelectedPageChanging(object sender, DevExpress.XtraTab.TabPageChangingEventArgs e)
        {
            tabKQ_SelectedPageChanged(sender,e);
        }

        private void tabKQ_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            int ss1 = 0;            
            ss1 = DateTime.Compare(cDate, DateTime.Today);
            if (ss1 < 0)//qua ngay
            {
                ptnButtonLXS.Enabled = false;               
                btnChupHinh.Enabled = false;
                pnlKQ.Enabled = false;
            }
            else 
            {
                ptnButtonLXS.Enabled = true;                
                btnChupHinh.Enabled = true;
                pnlKQ.Enabled = true;
                btnLuuKetQua.Enabled = false;
            } 
        }

        private void frmKetQua_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F2:
                    SendKeys.Send("{TAB}");
                    btnCapnhat_Click(sender, e);
                    break;
                case Keys.F3:
                    if (btnLuuKetQua.Enabled == true)
                    {
                        SendKeys.Send("{TAB}");
                        btnLuuKetQua_Click(sender, e);
                    }
                    break;
                case Keys.F4:
                    if (btnSuaKQ.Enabled == true)
                        btnSuaKQ_Click(sender, e);
                    break;
                case Keys.F9:
                    btnInKQ_Click(sender, e);
                    break;
             
                case Keys.F12:
                    if (!txtsotieuban.Text.Trim().Equals(""))
                    {
                        btnNext_Click(sender, e);
                        SendKeys.Send("{TAB}");
                    }
                    break;
                case Keys.F11:                  
                    if (!txtsotieuban.Text.Trim().Equals("") && btnPrevious.Enabled == true)
                        btnPrevious_Click(sender, e);
                    break;
            } 
        }

        private void btnXoaH1_Click(object sender, EventArgs e)
        {
            try
            {
                xoaHinh(ref picCL1, ref bmHinh1, txtsotieuban.Text.Trim(), "X100");
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH- " + ex.Message, "Thông Báo");
            }
        }

        private void btnXoaH2_Click(object sender, EventArgs e)
        {
            try
            {
                xoaHinh(ref picCL2, ref bmHinh2, txtsotieuban.Text.Trim(), "X400");
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH- " + ex.Message, "Thông Báo");
            }
        }

        private void txtViThe1_Leave(object sender, EventArgs e)
        {
            this.txtViThe1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtViThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtViThe1_Enter(object sender, EventArgs e)
        {
            this.txtViThe1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtViThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtDaiThe1_Enter(object sender, EventArgs e)
        {
            this.txtDaiThe1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtDaiThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtDaiThe1_Leave(object sender, EventArgs e)
        {
            this.txtDaiThe1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtDaiThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtKetLuan1_Leave(object sender, EventArgs e)
        {
            this.txtKetLuan1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtKetLuan1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtKetLuan1_Enter(object sender, EventArgs e)
        {
            this.txtKetLuan1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtKetLuan1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtsotieuban_EditValueChanged(object sender, EventArgs e)
        {
            
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            int numCur = 0, numPrev = 0;
            string pre = "";
            if (txtsotieuban.Text.ToUpper() == "___-_____")
            {
                return;
            }
            else
            {
                numCur = int.Parse(Right(txtsotieuban.Text, hensu.LengTeBao));
            }
            if (numCur <= 2)
                btnPrevious.Enabled = false;
            numPrev = numCur - 1;
            pre = Left(txtsotieuban.Text.ToUpper(), 4);
            txtsotieuban.Text = pre + numPrev.ToString("00000");

            btngo_Click(sender, e);     
        }

        private void btngo_Click(object sender, EventArgs e)
        {
            string SoTieuBan = txtsotieuban.Text;
            if (SoTieuBan.Equals(""))
                return;
            Xn = new TTXacNhanDTO();
            DataTable dt = GetThongTinSearchBUS.SearchDaXacNhanBySoTB(SoTieuBan);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    txtSoHS.Text = dt.Rows[0]["SoHS"].ToString();
                    Xn.SoHS = txtSoHS.Text;

                    txtSoBN.Text = dt.Rows[0]["SoBN"].ToString();
                    Xn.SoBN = dt.Rows[0]["SoBN"].ToString();

                    txtSoNVien.Text = dt.Rows[0]["sonhapvien"].ToString();
                    Xn.SoNV = dt.Rows[0]["sonhapvien"].ToString();

                    txtHoTen.Text = dt.Rows[0]["HoTen"].ToString();
                    Xn.HoTen = dt.Rows[0]["HoTen"].ToString();

                    txtGioi.Text = dt.Rows[0]["gioi"].ToString();
                    Xn.Gioi = bool.Parse(dt.Rows[0]["GioiTinh"].ToString());

                    txtTuoi.Text = dt.Rows[0]["namsinh"].ToString()
                                 + "(" + dt.Rows[0]["tuoi"].ToString() + " Tuổi)";
                    Xn.NamSinh = int.Parse(dt.Rows[0]["namsinh"].ToString());
                    Xn.Tuoi = int.Parse(dt.Rows[0]["tuoi"].ToString());

                    txtDichVu.Text      = dt.Rows[0]["tendvu"].ToString();
                    Xn.TenDVu           = dt.Rows[0]["tendvu"].ToString();

                    txtNghe.Text        = dt.Rows[0]["DienThoai"].ToString();
                    Xn.Nghe             = dt.Rows[0]["DienThoai"].ToString();

                    comDonVi.EditValue    = dt.Rows[0]["madonvi"].ToString();
                    Xn.TenDViChiDinh    = dt.Rows[0]["tendonvi"].ToString();

                    txtChuanDoan.Text   = dt.Rows[0]["chandoan"].ToString();
                    Xn.ChuanDoan        = dt.Rows[0]["chandoan"].ToString();

                    combscd.EditValue = dt.Rows[0]["idbscd"].ToString();
                    comPTV.Text = dt.Rows[0]["ptvid"].ToString();

                    Xn.NgayLayMau   = DateTime.Parse(dt.Rows[0]["ngaylaymau"].ToString());
                    Xn.NgayNhan     = DateTime.Parse(dt.Rows[0]["ngaynhan"].ToString());
                    comDViGuiMau.EditValue = dt.Rows[0]["IDDViGuiMau"].ToString();
                    comDonVi.EditValue = dt.Rows[0]["madonvi"].ToString();
                    IDBacSiCD.Text = dt.Rows[0]["BSiChiDinh"].ToString();
                    //PTVien.Text = dt.Rows[0]["ptvid"].ToString();
                    Xn.DVuCode = dt.Rows[0]["dvucode"].ToString();
                    lblDVCode.Text = Xn.DVuCode;
                    lblLoaiBN.Text = dt.Rows[0]["LoaiBN"].ToString();
                    CreateDir();
                    flagLuu = 1;
                    flagKQ = 1;
                }
                else
                {
                    initControl(this);
                }
            }
            LoadHinh();
            loadKQ();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            int numCur = 0, numNext = 0;
            string pre = "";
            if (txtsotieuban.Text.ToUpper() == "___-_____")
            {
                return;
            }
            else
            {
                numCur = int.Parse(Right(txtsotieuban.Text, hensu.LengTeBao));
            }
            if (numCur >= 1)
                btnPrevious.Enabled = true;
            numNext = numCur + 1;

            pre = Left(txtsotieuban.Text.ToUpper(), 4);
            txtsotieuban.Text = pre + numNext.ToString("00000");

            btngo_Click(sender, e);     
        }
        /// <summary>
        /// Lay chuoi tu phai sang theo leng truyen vao
        /// </summary>
        /// <param name="value">chuoi can cat</param>
        /// <param name="length">chieu dai can cat</param>
        /// <returns>chuoi can cat</returns>
        public string Right(string value, int length)
        {
            return value.Substring(value.Length - length);
        }
        /// <summary>
        /// hàm lấy chuỗi từ trái sang
        /// </summary>
        /// <param name="value">giá trị của chuỗi cần cắt</param>
        /// <param name="length">chiều dài cảu chuỗi con</param>
        /// <returns>cuỗi cần lấy</returns>
        public string Left(string value, int length)
        {
            return value.Substring(0, length);
        }

        private void btnLamMoi_Click(object sender, EventArgs e)
        {
            frmKetQua_Load(sender, e);
        }

        private void txtViThe1_Validated(object sender, EventArgs e)
        {
            string vithe = txtViThe1.Text;
            string[] words = vithe.Split(new string[] { "\r\n\r\n", "KEÁT LUAÄN:" }, StringSplitOptions.None);
            if (words.Length == 3)
            {
                txtViThe1.Text = words[0];
                txtKetLuan1.Text = words[2].Trim();
            }
        }

        private void txtsotieuban_Validated(object sender, EventArgs e)
        {
            btngo_Click(sender, e);
            txtsotieuban.Text = txtsotieuban.Text.ToUpper();
        }

        private void txtsotieuban_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            //string SoTB = txtsotieuban.Text;
            //string MaHieu = Left(SoTB, 1);
            //if (MaHieu != hensu.TienToFNA)
            //{
            //    MessageBox.Show("Bạn phải nhập số tiêu bản của FNA!","Thông báo");
            //    txtsotieuban.Text = "C";
            //    return;
            //}
        }

        private void txtsotieuban_Leave(object sender, EventArgs e)
        {
            string SoTB = txtsotieuban.Text;
            string MaHieu = Left(SoTB, 1);
            if (MaHieu.ToUpper() != hensu.TienToFNA)
            {
                MessageBox.Show("Bạn phải nhập số tiêu bản của FNA!", "Thông báo");
                txtsotieuban.Text = "C";
                return;
            }
        }
    }
}